<?php

namespace App\Model;

use Illuminate\Database\Eloquent\Model;
use DiDom\Document;
use App\Model\FangzhouListBaidu;
class FangzhouDetailBaidu extends Model
{
      public static function get_baidu_detail($keyword,$key_id,$url){

      $from = "百度";
      $match = "/question\/(.*)\.html/U";
      preg_match($match, $url,$ids);
      
      if (!isset($ids[1])) {
        $match = "/question\/(.*)/";
        preg_match($match, $url,$ids);
        if (!isset($ids[1])) {
        return ;
        }
      }

      $flag_id = $ids[1];
      $FangzhouDetail = FangzhouDetailBaidu::where('flag_id',$flag_id)->where('from',$from)->first();
      if(!$FangzhouDetail||1){
        $document = new Document($url, true);
        $title_html = $document->find(".title h2");
        if(isset($title_html[0])){
          $title =   $title_html[0]->text();
          $answer_html = $document->find(".quality-content-detail");
          if(isset($answer_html[0])){
             $answer = $answer_html[0]->html();
          }else{
             $answer ='';
          }     
          $otherAnswer_html = $document->find(".full-content"); 
          $other_answer = [];
          if(count($otherAnswer_html)){
            foreach ($otherAnswer_html as $key => $value) {
              $other_answer[]=$value->text();          
            }
          }
          $FangzhouDetail = new FangzhouDetailBaidu;
          $FangzhouDetail->flag_id = $flag_id;
          $FangzhouDetail->key_id = $key_id;
          $FangzhouDetail->from = $from;
          $FangzhouDetail->keyword = $keyword;       
          $FangzhouDetail->save();
          $FangzhouListBaidu = new FangzhouListBaidu;
          $FangzhouListBaidu->detail_id = $FangzhouDetail->id;
          $FangzhouListBaidu->title = $title;
          $FangzhouListBaidu->answer = $answer;
          $FangzhouListBaidu->other_answer = json_encode($other_answer);
          $FangzhouListBaidu->save();
        }
      }   
    }
}
